using System;
using System.Collections.Generic;
using System.Text;
using Evolution.Engine.Interfaces;
using Microsoft.Xna.Framework;
using Evolution.Engine.Managers;
using Microsoft.Xna.Framework.Graphics;

namespace Evolution.Engine.Objects
{
    public class SkyBox : BaseObject, IChildRenderer, ILoadable
    {
		private TextureQuad[] _Sides;
		private string[] _Files;
		private Vector3[] _Offsets;

        public SkyBox(string[] textures, string name)
            : base(name)
        {
			_Files = textures;
			_Scale = new Vector3(500, 500, 500);
			_Sides = new TextureQuad[6];

			CreateSides();
			CalculateOffsets();
		}

        public void RenderChildren(GameTime gameTime)
        {
			Shader objShader = ShaderManager.Instance.GetShader(_Shader);

			objShader.Effect.Begin();
			foreach(EffectPass pass in objShader.Effect.CurrentTechnique.Passes)
            {
				for(int i = 0; i < 6; i++) 
                {
					_Sides[i].Position = CameraManager.Instance.ActiveCamera.Position + _Offsets[i];
					objShader.SetParameters(_Sides[i]);

					pass.Begin();
					_Sides[i].Render(gameTime);
					pass.End();
				}
			}
			objShader.Effect.End();
		}

		public override void LoadContent()
        {
			foreach(TextureQuad quad in _Sides) 
            {
				quad.LoadContent();
			}
		}

		private void CreateSides()
        {
			for(int i = 0; i < 6; i++) 
            {
				_Sides[i] = new TextureQuad(_Files[i], "Side" + i.ToString());
				_Sides[i].Scale = _Scale;
			}

			_Sides[0].Rotation = Quaternion.CreateFromAxisAngle(new Vector3(1, 0, 0), MathHelper.PiOver2);
			_Sides[1].Rotation = Quaternion.CreateFromAxisAngle(new Vector3(1, 0, 0), -MathHelper.PiOver2);
			_Sides[2].Rotation = Quaternion.CreateFromAxisAngle(new Vector3(0, 1, 0), MathHelper.PiOver2);
			_Sides[3].Rotation = Quaternion.CreateFromAxisAngle(new Vector3(0, 1, 0), -MathHelper.PiOver2);
			_Sides[5].Rotation = Quaternion.CreateFromAxisAngle(new Vector3(0, 1, 0), MathHelper.Pi);
		}

		private void CalculateOffsets()
        {
			_Offsets = new Vector3[6];

			_Offsets[0] = new Vector3(0,  0.5f, 0) * _Scale;
            _Offsets[1] = new Vector3(0, -0.5f, 0) * _Scale;
            _Offsets[2] = new Vector3(-0.5f, 0, 0) * _Scale;
            _Offsets[3] = new Vector3(0.5f, 0, 0) * _Scale;
            _Offsets[4] = new Vector3(0, 0, -0.5f) * _Scale;
            _Offsets[5] = new Vector3(0, 0, 0.5f) * _Scale;
		}
	}
}